import cv2
import numpy as np


def segment_characters(plate_image):
    # 二值化
    _, binary = cv2.threshold(plate_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

    # 查找轮廓
    contours = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    # 适应不同版本的OpenCV
    contours = contours[0] if len(contours) == 2 else contours[1]

    char_images = []
    for contour in contours:
        (x, y, w, h) = cv2.boundingRect(contour)
        if h > 0.5 * plate_image.shape[0]:  # 过滤掉太小的轮廓
            char_img = binary[y:y + h, x:x + w]
            char_images.append(char_img)

    # 按x坐标排序
    char_images.sort(key=lambda img: cv2.boundingRect(cv2.findNonZero(img))[0])

    return char_images